package com.example.cofeed.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.cofeed.R;
import com.example.cofeed.api.APIUrl;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Share;
import com.example.cofeed.util.MD5Util;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

;

/**
 * Created by mqwang on 2016/11/30.
 */
public class WebViewActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView mWebView;
    private String mUrl;
    private int mId;

    private static final String HELP = "https://app.cofeed.com/setting/help";

    private static final String PRICE = "https://app.cofeed.com/price";
    private static final String DIAGRAM = "https://app.cofeed.com/diagram";
    private static final String TOOL = "https://app.cofeed.com/tool";
    private static final String SEARCH = "https://app.cofeed.com/search/";
    private static final String FEEDBACK = "https://app.cofeed.com/suggestion/view";
    private static final String CONTACTUS = "https://app.cofeed.com/contactus/";
    private static final String SHANGJIA = "https://app.cofeed.com/favorite/supply_list";
    private static final String ABOUT_US = "https://app.cofeed.com/about";
    private static final String SUGGESTION = "https://app.cofeed.com/suggestion/get_list";

    private int mType;
    private String mTitle;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected boolean isNeedTitleBar() {
        mType = getIntent().getIntExtra(IntentKeyConstant.TYPE, 0);
        if (mType == 6) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {

        setMainSubTitle("", R.mipmap.ic_share);

        mWebView.requestFocus(View.FOCUS_DOWN);


        mUrl = getIntent().getStringExtra(IntentKeyConstant.URL);
//        fullUrl = "http://www.deter294.cn/#8848";
//        String title = getIntent().getStringExtra(IntentKeyConstant.URL_TITLE);
//       if (!ObjectUtils.isEmpty(title)){
//           setMainTitle(title);
//       }

        mId = getIntent().getIntExtra(IntentKeyConstant.ID, 0);

        mWebView = (WebView) findViewById(R.id.webview);

        // 解决webview的无法全屏显示的问题
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        // 运行运行JavaScript脚本
        mWebView.getSettings().setJavaScriptEnabled(true);

        mWebView.getSettings().setJavaScriptEnabled(true); // 启用js
        mWebView.getSettings().setBlockNetworkImage(false); // 解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        // 监听脚本
//        mWebView.addJavascriptInterface(new JavaScriptInterface(), "chinaj");

        //使用html5的 localStorage
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebView.getSettings().setAppCachePath(appCachePath);
        mWebView.getSettings().setAllowFileAccess(true);

        mWebView.getSettings().setAppCacheEnabled(true);


        // 对于连接状态的不同处理
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                LogUtils.e("msg--------- " + url);
                if (url.contains("type")) {
                    String type = getValueByName(url, "type");
                    Intent intent = null;

                    String catid = getValueByName(url, "catid");
                    String urlByname = getValueByName(url, "url");

                    switch (type) {
                        case "1":
                            ActivityUtils.startActivity(LoginActivity.class);
                            break;
                        //文章品种列表  type=2&catid=品种ID 文章详细页会有文章的相应品种频道，当点的击时能直接跳转过去
                        case "2":
                            intent = new Intent();
                            intent.putExtra("catid", catid);
                            setResult(RESULT_OK, intent);
                            finish();
                            break;
                        //文章频道列表  type=3&chlid=频道ID 文章详细页会有文章的相应品种频道，当点的击时能直接跳转过去
                        case "3":
                            String chlid = getValueByName(url, "chlid");
                            intent = new Intent();
                            intent.putExtra("chlid", chlid);
                            setResult(RESULT_OK, intent);
                            finish();
                            break;
                        //打开文章详情  type=4&infoid=文章ID&url=文章地址   文章详细页会有相关推荐，当点文章时，因为验证需要，所以需要像原来文章列表那样触发
                        case "4":
                            String infoid = getValueByName(url, "infoid");
                            intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKeyConstant.ID, Integer.valueOf(infoid));
                            intent.putExtra(IntentKeyConstant.URL, urlByname);
                            startActivity(intent);
                            break;
                        //供求品种列表  type=5&catid=品种ID  供求详细页上有章详细页会有文章的相应品种，当点的击时能直接跳转到供求列表上对应的品种
                        case "5":
                            intent = new Intent();
                            intent.putExtra("catid", catid);
                            setResult(RESULT_OK, intent);
                            finish();
                            break;
                        //打开供求详情  type=6&supplyid=供求id&url=供求地址 供求详细页会有相关推荐，当点文章时，因为验证需要，所以需要像原来文章列表那样触发
                        case "6":
                            String supplyid = getValueByName(url, "supplyid");
                            intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKeyConstant.ID, Integer.valueOf(supplyid));
                            intent.putExtra(IntentKeyConstant.URL, urlByname);
                            intent.putExtra(IntentKeyConstant.TYPE, -1);
                            startActivity(intent);
                            break;
                        case "7":
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("sign", getSign(params));
                            mWebView.loadUrl(urlByname, params);
                            break;
                        case "8":
                            String content = getValueByName(url, "content");
                            intent = new Intent(mContext, ShareActivity.class);
                            intent.putExtra(IntentKeyConstant.URL, urlByname);
                            intent.putExtra(IntentKeyConstant.NAME, content);
                            startActivity(intent);
                            break;
                        case "9":
                            String phone = getValueByName(url, "phone");
                            PhoneUtils.dial(phone);
                            break;
                        case "10":
                            finish();
                            break;
                        default:
                            return super.shouldOverrideUrlLoading(view, url);


                    }
                    return true;

                }


                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                result();

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            }

        });
//        setMainTitle("文章详情");
        WebChromeClient wvcc = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitle = title;
                setMainTitle(title);
            }

        };
        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(wvcc);
//        mWebView.loadUrl(fullUrl);
        Map<String, String> params = new HashMap<String, String>();

        if (mType > 0) {
            switch (mType) {
                case 1:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(HELP, params);
                    break;
                case 11:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(ABOUT_US, params);
                    break;
                case 2:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(PRICE, params);
                    break;
                case 3:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(DIAGRAM, params);
                    break;
                case 4:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(TOOL, params);
                    break;
                //普通url
                case 5:
                    mWebView.loadUrl(mUrl);
                    break;
                //搜索界面
                case 6:
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(SEARCH, params);
                    break;
                //意见反馈
                case 7:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(FEEDBACK, params);
                    break;
                //联系我们
                case 8:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(CONTACTUS, params);
                    break;
                case 9:
                    setMainSubTitle("", 0);
                    mWebView.loadUrl(mUrl);
                    break;
                case 10:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(SHANGJIA, params);
                    break;
                case 12:
                    setSubTitle("");
                    params.put("sign", getSign(params));
                    mWebView.loadUrl(SUGGESTION, params);
                    break;
            }
        } else {
            if (mType == -2) {
                setMainSubTitle("", 0);

                if (!mUrl.contains("https://app.cofeed.com")) {
                    mUrl = "https://app.cofeed.com" + mUrl;
                    String token = SPUtils.getInstance().getString(SputilsConstant.TOKEN);
                    params.put("accesstoken", token);
                    params.put("signcode", DeviceUtils.getAndroidID());
                    mWebView.loadUrl(mUrl, params);

                } else {
                    mWebView.loadUrl(mUrl);

                }
                return;
            }
            //供求详情
            if (mType == -1) {
                params.put("id", mId + "");
            } else {
                params.put("infoid", mId + "");
            }

            params.put("sign", getSign(params));

            if (mUrl.contains("http")) {
                mWebView.loadUrl(mUrl, params);
            } else {
                mWebView.loadUrl(APIUrl.BASE_URL + mUrl, params);

            }
        }

    }

    private void result() {
        int headingFontSize = SPUtils.getInstance().getInt(SputilsConstant.HEADING_FONT_SIZE);
        //小：small、标准：mid、大：big、极大：high、超大：max
        switch (headingFontSize) {
            case 0:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'small'" + ")");
                break;
            case 1:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'mid'" + ")");
                break;
            case 2:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'big'" + ")");
                break;
            case 3:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'high'" + ")");
                break;
            case 4:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'max'" + ")");
                break;
            default:
                mWebView.loadUrl("javascript:fontSizeInit(" + "'mid'" + ")");
                break;
        }
    }

    private Share share;

    @Override
    protected void onRightClickAction() {
        super.onRightClickAction();

        if (mId == 0) {
            return;
        }
        if (share == null) {
            //供求列表
            if (mType == -1) {
                ApiService.supply_share(this, mId, new DialogCallback<LzyResponse<Share>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Share>> response) {
                        share = response.body().data;
                        Intent shareIntent = new Intent(mContext, ShareActivity.class);
                        shareIntent.putExtra(IntentKeyConstant.URL, share.urlpath);
                        shareIntent.putExtra(IntentKeyConstant.TITLE, share.title);
                        shareIntent.putExtra(IntentKeyConstant.SMALLIMGS, share.icon);
                        startActivity(shareIntent);
                    }
                });
            } else {
                ApiService.article_share(this, mId, new DialogCallback<LzyResponse<Share>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Share>> response) {
                        share = response.body().data;
                        Intent shareIntent = new Intent(mContext, ShareActivity.class);
                        shareIntent.putExtra(IntentKeyConstant.URL, share.urlpath);
                        shareIntent.putExtra(IntentKeyConstant.TITLE, share.title);
                        if (mType != -1) {
                            shareIntent.putExtra(IntentKeyConstant.NAME, share.description);
                            shareIntent.putExtra(IntentKeyConstant.SMALLIMGS, share.smallimgs);
                        } else {
                            shareIntent.putExtra(IntentKeyConstant.SMALLIMGS, share.icon);

                        }
                        startActivity(shareIntent);
                    }
                });
            }

        } else {
            Intent shareIntent = new Intent(mContext, ShareActivity.class);
            shareIntent.putExtra(IntentKeyConstant.URL, share.urlpath);
            shareIntent.putExtra(IntentKeyConstant.TITLE, share.title);
            if (mType != -1) {
                shareIntent.putExtra(IntentKeyConstant.NAME, share.description);
            }
            shareIntent.putExtra(IntentKeyConstant.SMALLIMGS, share.smallimgs);
            startActivity(shareIntent);
        }


//        UMImage localImage = new UMImage(this, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
//
//        String url = getIntent().getStringExtra(IntentKeyConstant.URL);
//
//        String content = getIntent().getStringExtra(IntentKeyConstant.NAME);
//        UMWeb web;
//        if (ObjectUtils.isNotEmpty(url)) {
//            url = url.replace("//app", "/m");
//            web = new UMWeb(url);//网址
//        } else {
//            web = new UMWeb("http://m.cofeed.com/cofapp/cofsms/");//网址
//        }
//
//        web.setTitle("天下粮仓");//标题
//        web.setThumb(localImage);  //缩略图
//        if (ObjectUtils.isEmpty(content)) {
//            content = "天下粮仓是由天下粮仓网旗下APP，专业粮油饮料行业打造的短讯客户端产品，集合短信服务与手机客户端的优点,是一款可以根据您自身需求量身定制信息推送服务应用软件！操作简单明了,接收信息内容更加及时方便快捷。万千资讯，尽在“掌”握，助您抢占市场先机!";
//        }
//        web.setDescription(content);
//        new ShareAction(this).withText("ad").setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.SMS)
//                .setCallback(null).open();

    }

    /**
     * 统一签名
     *
     * @param params
     * @return
     */
    public static String getSign(Map<String, String> params) {

        String token = SPUtils.getInstance().getString(SputilsConstant.TOKEN);
        if (!TextUtils.isEmpty(token)) {
            params.put("accesstoken", token);
        }
        params.put("signcode", DeviceUtils.getAndroidID());
        params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Map.Entry<String, String>> infoIds = new ArrayList<>(params.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey().trim()).compareTo(o2.getKey().trim());
            }
        });
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : infoIds) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.append("key=" + "7957Cc718Fd459A7bCc5eE039c3d0292");
        String str = sb.toString();
        String sign = MD5Util.encodeLowercaseHex(str);
        return sign;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /***
     * 获取url 指定name的value;
     * @param url
     * @param name
     * @return
     */
    public static String getValueByName(String url, String name) {
        String result = "";
        String temp = "";
        if (url.contains("?")) {
            int index = url.indexOf("?");
            temp = url.substring(index + 1);
        } else {
            int index = url.indexOf("/");
            temp = url.substring(index + 2);
        }

        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}
